package component.menu
{
	import component.menu.data.MenuItemData;
	import component.menu.item.MenuItem;
	
	import flash.events.MouseEvent;
	
	import obecto.core.FLContainer;
	import obecto.transition.State;
	import obecto.transition.TransitionsManager;

	[Event(name="select", type="component.menu.MenuEvent")]
	[Event(name="deselect", type="component.menu.MenuEvent")]
	public class MenuClass extends FLContainer
	{
		public var itemRenderer : Class = MenuItem;
		
		protected var _itemsData : Array;
		public function set itemsData(value : Array) : void
		{
			if (value != null && value != _itemsData)
			{
				_itemsData = value;
				if (initialized)
				{
					initializeMenuItems();
				}
			}
		}
		
		public var selectedData : MenuItemData;
		
		protected var transitionsManager : TransitionsManager;
		
		[Bindable] protected var collapsedState : State;
		[Bindable] protected var expandedState : State;
		
		public function MenuClass()
		{
			super();
			
			_contentChildren = new Array();
		}
		
		public function show() : void 
		{
			transitionsManager.state = expandedState;
		}
		
		public function hide() : void 
		{
			transitionsManager.state = collapsedState;
		}
		
		override protected function initialize() : void
		{
			super.initialize();
			if (_itemsData != null)
			{
				initializeMenuItems();
			}
		}
		
		protected function initializeMenuItems() : void 
		{
			for each (var itemData : MenuItemData in _itemsData)
			{
				var item : MenuItem = MenuItem(new itemRenderer());
				item.data = itemData;
				
				addContentChild(item);
				
				item.addEventListener(MouseEvent.CLICK, handleItemClick);
			}
			
			layout.items = _contentChildren;
		}
		
		protected function selectItem(itemData : MenuItemData) : void 
		{
			deselectAllItems();
			
			itemData.selected = true;
			
			selectedData = itemData;
		}
		
		protected function deselectItem(itemData : MenuItemData) : void 
		{
			itemData.selected = false;
			
			selectedData = null;
		}
		
		protected function deselectAllItems() : void 
		{
			for each (var itemData : MenuItemData in _itemsData)
			{
				itemData.selected = false;
			}
			
			selectedData = null;
		}
		
		protected function dispatchSelectEvent(itemData : MenuItemData) : void 
		{
			dispatchEvent(new MenuEvent(MenuEvent.SELECT, itemData, true));
		}
		
		protected function dispatchDeselectEvent(itemData : MenuItemData) : void 
		{
			dispatchEvent(new MenuEvent(MenuEvent.DESELECT, itemData, true));
		}
		
		protected function handleItemClick(e : MouseEvent) : void 
		{
			var menuItem : MenuItem = MenuItem(e.target);
			if (menuItem.enabled)
			{
				if (menuItem.selected)
				{
					selectItem(menuItem.data);
					dispatchSelectEvent(menuItem.data);
				}
				else
				{
					deselectItem(menuItem.data);
					dispatchDeselectEvent(menuItem.data);
				}
			}
		}
		
	}
}